package com.wanban.downloader.utils

import android.widget.ArrayAdapter
import com.blankj.utilcode.util.FileUtils
import com.blankj.utilcode.util.ThreadUtils
import com.wanban.downloader.db.DownloadEntity
import com.wanban.downloader.db.M3u8VideoDownloadDatabaseHelper
import com.wanban.downloader.model.Status

object DatabaseUtils {

    private val dbHelper by lazy { M3u8VideoDownloadDatabaseHelper(ContextProvider.application) }



    fun getAlbumDownloads(video: Long, success: (task: ArrayList<DownloadEntity>) -> Unit){
        ThreadUtils.executeBySingle(object : ThreadUtils.Task<ArrayList<DownloadEntity>>() {
            override fun doInBackground(): ArrayList<DownloadEntity> {
                return dbHelper.getDownloadTaskByVideoId(video) ?:ArrayList()
            }
            override fun onSuccess(result: ArrayList<DownloadEntity>) {
                success(result)
            }
            override fun onCancel() {}
            override fun onFail(t: Throwable) {}
        })
    }

    fun getSuccessDownloadTasks(success: (task: ArrayList<DownloadEntity>) -> Unit){
        ThreadUtils.executeBySingle(object : ThreadUtils.Task<ArrayList<DownloadEntity>>() {
            override fun doInBackground(): ArrayList<DownloadEntity> {
                return dbHelper.successDownloads ?:ArrayList()
            }
            override fun onSuccess(result: ArrayList<DownloadEntity>) {
                success(result)
            }
            override fun onCancel() {}
            override fun onFail(t: Throwable) {}
        })
    }


    fun getDownloadTask(url: String, success: (task: DownloadEntity?) -> Unit){
        ThreadUtils.executeBySingle(object : ThreadUtils.Task<DownloadEntity?>() {
            override fun doInBackground(): DownloadEntity? {
                return dbHelper.isAddedTask(url)
            }
            override fun onSuccess(result: DownloadEntity?) {
                success(result)
            }
            override fun onCancel() {}
            override fun onFail(t: Throwable) {}
        })
    }

    fun getDownloadTask(video: Long, episode: Int, sourceId: Int, success: (task: DownloadEntity?) -> Unit){
        ThreadUtils.executeBySingle(object : ThreadUtils.Task<DownloadEntity?>() {
            override fun doInBackground(): DownloadEntity? {
                return dbHelper.getDownloadTask(video, episode, sourceId)
            }
            override fun onSuccess(result: DownloadEntity?) {
                success(result)
            }
            override fun onCancel() {}
            override fun onFail(t: Throwable) {}
        })
    }

    fun hasDownloadingTask(success: (hasDownloading: Boolean) -> Unit){
        ThreadUtils.executeBySingle(object : ThreadUtils.Task<Boolean>() {
            override fun doInBackground(): Boolean {
               return dbHelper.hasDownloadingTask()
            }
            override fun onSuccess(result: Boolean) {
                success(result)
            }
            override fun onCancel() {}
            override fun onFail(t: Throwable) {}
        })
    }

    fun getAllDownloadTask(): ArrayList<DownloadEntity> {
        return dbHelper.downloadInfos as ArrayList<DownloadEntity>? ?: return ArrayList()
    }

    fun getDownloadTask(complete: (tasks: ArrayList<DownloadEntity>) -> Unit) {
        ThreadUtils.executeBySingle(object : ThreadUtils.Task<ArrayList<DownloadEntity>>() {
            override fun doInBackground(): ArrayList<DownloadEntity> {
                val result = dbHelper.downloadInfos ?: return ArrayList()
                // 处理存在标签是DELETE的task
                val deleteTasks = result.filter { it.state == Status.DELETE }
                if (deleteTasks.isNotEmpty()) { // 这种下载不应该存在，存在的话也是bug
                    deleteTasks.forEach {
                        //从表中删除
                        dbHelper.deleteDownloadItemByUrl(it.url)
                        // 删除文件
                        FileUtils.deleteAllInDir(FileDownloadUtils.getOrCreateVideoRootFileDirPath(it.videoName))
                    }
                    result.removeAll(deleteTasks)
                }
//                val runningTask = result.filter { it.state != Status.SUCCESS }
//                runningTask.forEach { // 重置状态
//                    if (it.state != Status.STOP && it.state != Status.ERROR) {
//                        it.state = Status.PENDING
//                    }
//                }

                result.forEach {
                    if (it.state == Status.PREPARE || it.state == Status.START || it.state == Status.DOWNLOADING) {
                        it.state = Status.PENDING
                    }
                }

                return result as ArrayList<DownloadEntity>
            }
            override fun onSuccess(result: ArrayList<DownloadEntity>) {
                complete(result)
            }
            override fun onCancel() {}
            override fun onFail(t: Throwable) {}
        })
    }

    fun insertOrUpdateTask(entity: DownloadEntity) {
        ThreadUtils.executeBySingle(object : ThreadUtils.Task<Long>() {
            override fun doInBackground(): Long {
                return dbHelper.markDownloadUpdateEvent(entity)
            }
            override fun onSuccess(result: Long?) {}
            override fun onCancel() {}
            override fun onFail(t: Throwable) {}
        })
    }

    fun deleteTask(url: String){
        ThreadUtils.executeBySingle(object : ThreadUtils.Task<Int>() {
            override fun doInBackground(): Int {
                return dbHelper.deleteDownloadItemByUrl(url)
            }
            override fun onSuccess(result: Int?) {}
            override fun onCancel() {}
            override fun onFail(t: Throwable) {}
        })
    }
}